<template>
  <div class="box">
    <div class="material-information">
      <el-form
        ref="ruleFormRef"
        style="padding: 2rem 5rem; display: flex; flex-wrap: wrap; justify-content: space-between; width: 80%"
        :model="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="供应商编码" prop="materialId" class="materialinput">
          <el-input v-model="suppliersInquire.erpCode" placeholder="请输入供应商编码" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="materialId" class="materialinput">
          <el-input v-model="suppliersInquire.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="邀约状态" prop="materialType" class="materialselect" style="">
          <el-select v-model="ruleForm.materialType" placeholder="请选择邀约状态">
            <el-option label="已关联" value="rawmaterials" />
            <el-option label="已拒绝" value="norawmaterials" />
            <el-option label="待确认" value="norawmaterials" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="baseinfobtn">
        <div class="baseinfobtncenter">
          <div class="baseinfobtn-1" @click="suppliersSelect">
            <el-icon style="position: relative; top: 2px" color="#fff"><Search /></el-icon>
            <span>查询</span>
          </div>
          <div class="baseinfobtn-2" @click="suppliersReset">
            <el-icon style="position: relative; top: 2px"><Refresh /></el-icon>
            <span>重置</span>
          </div>
        </div>
      </div>
    </div>
    <div class="material-addinformation">
      <div class="baseinfobtn" style="flex-direction: row-reverse; padding-right: 2rem">
        <div class="baseinfobtncenter" style="margin: 0">
          <div class="baseinfobtn-1" @click="addform">
            <el-icon color="#fff" :size="16" class="iconsy"><Plus /></el-icon>
            <span>新增</span>
          </div>
          <div class="baseinfobtn-2" @click="importingOrder = true">
            <el-icon :size="16" class="iconsy"><UploadFilled /></el-icon>
            <span>导入</span>
          </div>
          <div :class="multipleSelection.length == 1 ? 'baseinfobtn-2' : 'baseinfobtn-2b'">
            <el-icon :size="16" class="iconsy"><Setting /></el-icon>
            <span>供应商配置</span>
          </div>
          <div :class="multipleSelection.length == 1 ? 'baseinfobtn-2' : 'baseinfobtn-2b'" @click="editform">
            <el-icon :size="16" class="iconsy"><EditPen /></el-icon>
            <span>编辑</span>
          </div>
          <div :class="multipleSelection.length > 0 ? 'baseinfobtn-2' : 'baseinfobtn-2b'" @click="delform">
            <el-icon :size="16" class="iconsy"><Delete /></el-icon>
            <span>删除</span>
          </div>
        </div>
      </div>
      <div style="padding: 3rem; padding-top: 15px">
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          size="default"
          :header-cell-style="{ backgroundColor: '#F8F8F9', color: '#333', fontSize: '14px' }"
          @select="materialone"
          @select-all="materialall"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="供应商编码">
            <template #default="scope">
              <span
                style="color: #578c43; text-decoration: underline; cursor: pointer"
                @click="gomultipleinfo(scope.row.erpCode)"
              >
                {{ scope.row.erpCode }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="供应商名称">
            <template #default="scope">
              <span style="color: #578c43">{{ scope.row.supplierName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="地址">
            <template #default="scope">{{ scope.row.address }}</template>
          </el-table-column>
          <el-table-column label="邀约状态" width="120">
            <template #default="scope">
              <div :class="scope.row.tenant_state === '0' || scope.row.tenant_state === '1' ? 'yuan' : 'yuanb'">
                {{
                  scope.row.tenant_state === '0' || scope.row.tenant_state === '1'
                    ? scope.row.tenant_state === '0'
                      ? '待确认'
                      : '已关联'
                    : '已拒绝'
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="企业号">
            <template #default="scope">{{ scope.row.enterprisenum }}</template>
          </el-table-column>
          <el-table-column label="统一信用代码">
            <template #default="scope">{{ scope.row.creditCode }}</template>
          </el-table-column>
          <el-table-column label="语言">
            <template #default="scope">{{ scope.row.language }}</template>
          </el-table-column>
          <el-table-column label="电话">
            <template #default="scope">{{ scope.row.phone }}</template>
          </el-table-column>
          <el-table-column label="传真">
            <template #default="scope">{{ scope.row.fax }}</template>
          </el-table-column>
          <el-table-column label="邮箱">
            <template #default="scope">{{ scope.row.email }}</template>
          </el-table-column>
          <el-table-column label="增值税登记号">
            <template #default="scope">{{ scope.row.vatRegistrationNumber }}</template>
          </el-table-column>
          <el-table-column label="邮编">
            <template #default="scope">{{ scope.row.postcode }}</template>
          </el-table-column>
        </el-table>
        <div style="float: right; margin: 20px 0">
          <el-pagination
            v-model:current-page="suppliersInquire.currentPage"
            v-model:page-size="suppliersInquire.pageSize"
            :page-sizes="[10, 20, 50]"
            :size="size"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="suppliersInquire.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :title="iseditmultiple ? '编辑' : '新增'" width="1200">
      <div>
        <div class="material-information">
          <el-form
            ref="ruleFormRef"
            style="padding: 2rem 5rem; display: flex; flex-wrap: wrap; justify-content: space-between; padding-top: 0"
            :model="ruleFormedit"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="ERP编号" prop="erpCode" class="materialinputb">
              <el-input v-model="ruleFormedit.erpCode" show-word-limit placeholder="请输入ERP编号" disabled />
            </el-form-item>
            <el-form-item label="供应商名称" prop="supplierName" class="materialinputb">
              <el-input
                v-model="ruleFormedit.supplierName"
                maxlength="64"
                show-word-limit
                placeholder="请输入供应商名称"
              />
            </el-form-item>
            <el-form-item label="电话" prop="phone" class="materialinputb">
              <el-input v-model="ruleFormedit.phone" maxlength="20" show-word-limit placeholder="请输入电话" />
            </el-form-item>
            <el-form-item label="增值税登记号" prop="vatRegistrationNumber" class="materialinputb">
              <el-input
                v-model="ruleFormedit.vatRegistrationNumber"
                maxlength="50"
                show-word-limit
                placeholder="请输入增值税登记号"
              />
            </el-form-item>
            <el-form-item label="国家" prop="country" class="materialselectb" style="">
              <el-select v-model="ruleFormedit.country" placeholder="请选择国家">
                <el-option label="中国" value="rawmaterials" />
                <el-option label="美国" value="norawmaterials" />
                <el-option label="日本" value="norawmaterials" />
                <el-option label="韩国" value="norawmaterials" />
              </el-select>
            </el-form-item>
            <el-form-item label="省份" prop="province" class="materialselectb" style="">
              <el-select v-model="ruleFormedit.province" placeholder="请选择省份">
                <el-option label="福建省" value="rawmaterials" />
                <el-option label="上海" value="norawmaterials" />
                <el-option label="北京" value="norawmaterials" />
              </el-select>
            </el-form-item>
            <el-form-item label="城市" prop="city" class="materialselectb" style="">
              <el-select v-model="ruleFormedit.city" placeholder="请选择城市">
                <el-option label="泉州" value="rawmaterials" />
                <el-option label="厦门" value="norawmaterials" />
                <el-option label="福州" value="norawmaterials" />
              </el-select>
            </el-form-item>
            <el-form-item label="街道门牌" prop="streetSign" class="materialinputb">
              <el-input v-model="ruleFormedit.streetSign" maxlength="64" show-word-limit placeholder="请输入街道门牌" />
            </el-form-item>
            <el-form-item label="语言" prop="lange" class="materialselectb" style="">
              <el-select v-model="ruleFormedit.language" placeholder="语言">
                <el-option label="中文" value="rawmaterials" />
                <el-option label="英语" value="norawmaterials" />
              </el-select>
            </el-form-item>
            <el-form-item label="传真" prop="fax" class="materialinputb">
              <el-input v-model="ruleFormedit.fax" maxlength="50" show-word-limit placeholder="请输入传真" />
            </el-form-item>
            <el-form-item label="邮编" prop="postcode" class="materialinputb">
              <el-input v-model="ruleFormedit.postcode" maxlength="50" show-word-limit placeholder="请输入邮编" />
            </el-form-item>
            <el-form-item label="网址" prop="website" class="materialinputb">
              <el-input v-model="ruleFormedit.website" maxlength="50" show-word-limit placeholder="请输入网址" />
            </el-form-item>
            <el-form-item label="账号组" prop="accountGroup" class="materialinputb">
              <el-input v-model="ruleFormedit.accountGroup" maxlength="50" show-word-limit placeholder="请输入账号组" />
            </el-form-item>
            <el-form-item label="备注" prop="remark" class="materialinputb">
              <el-input
                v-model="ruleFormedit.headerDescription"
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入账号组"
              />
            </el-form-item>
          </el-form>
        </div>
        <el-menu :default-active="activeIndex" class="el-menu-demo nemulist" mode="horizontal" @select="handleSelect">
          <el-menu-item index="1">联系人信息</el-menu-item>
          <el-menu-item index="2">银行信息</el-menu-item>
        </el-menu>
        <div v-if="activeIndex == '1'" style="margin-top: 15px">
          <div class="addmaterialbtn" @click="addmatereal">
            <el-icon style="margin-right: 5px"><Plus /></el-icon>
            <span>添加一行</span>
          </div>
          <el-table
            :data="tableDataedit"
            border
            style="width: 100%"
            size="default"
            :header-cell-style="{ backgroundColor: '#F8F8F9', color: '#333', fontSize: '14px' }"
          >
            <el-table-column type="index" label="项目" align="center" width="90" />
            <el-table-column prop="factory" label="姓名">
              <template #default="scope">
                <el-input
                  v-model="scope.row.Deliverydays"
                  size="default"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入姓名"
                />
              </template>
            </el-table-column>
            <el-table-column prop="purchasgroup" label="电话">
              <template #default="scope">
                <el-input
                  v-model="scope.row.Deliverydays"
                  size="default"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入电话"
                />
              </template>
            </el-table-column>
            <el-table-column prop="Deliverydays" label="手机">
              <template #default="scope">
                <el-input
                  v-model="scope.row.Deliverydays"
                  size="default"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入手机"
                />
              </template>
            </el-table-column>
            <el-table-column prop="safestock" label="邮箱">
              <template #default="scope">
                <el-input
                  v-model="scope.row.safestock"
                  size="default"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入邮箱"
                />
              </template>
            </el-table-column>
            <el-table-column prop="profitcenter" label="备注">
              <template #default="scope">
                <el-input
                  v-model="scope.row.profitcenter"
                  size="default"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入备注"
                />
              </template>
            </el-table-column>
            <el-table-column prop="operation" label="操作" align="center" width="90">
              <template #default="scope">
                <el-button plain class="deltext" size="default" @click="delmatereal(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="default" type="primary" style="background-color: #578c43" @click="editmultiple">
            {{ iseditmultiple ? '编辑' : '新增' }}
          </el-button>
          <el-button size="default" @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog v-model="importingOrder" title="物料导入" width="800">
      <div>
        <el-upload
          class="upload-demo"
          drag
          multiple
          :limit="3"
          :data="attachmentId"
          :http-request="uploading"
          :headers="loadfileheaders"
        >
          <div class="el-upload__text">
            将文件拖到此处，或
            <span style="color: #578c43">点击上传</span>
          </div>
          <template #tip>
            <div class="el-upload__tip" style="text-align: center; margin-top: 10px">
              仅允许导入xls，xlsx格式文件。
              <span style="color: #578c43" @click="download">下载模板</span>
            </div>
          </template>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="default" type="primary" style="background-color: #578c43" @click="importingOrder = false">
            确认
          </el-button>
          <el-button size="default" @click="importingOrder = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { Action, ComponentSize, FormInstance, FormRules, TableColumnCtx, TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {
  suppliersSelectlist,
  suppliersTemplate,
  suppliersadd,
  suppliersdelete,
  suppliersedit,
  suppliersimports
} from '@/api/suppliers'

onMounted(() => {
  suppliersList()
})

//供应商数据
interface User {
  id: number
  erpCode: string
  supplierName: string
  address: string
  tenant_state: string
  enterprisenum: string
  creditCode: string
  language: string
  phone: string
  fax: string
  email: string
  vatRegistrationNumber: string
  postcode: string
}
const tableData = ref<User[]>([])
//分页
const size = ref<ComponentSize>('default')
const background = ref(true)
interface suppliers {
  currentPage: number
  pageSize: number
  total: number
  erpCode: string
  supplierName: string
}
const suppliersInquire = ref<suppliers>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  erpCode: '',
  supplierName: ''
})

const handleSizeChange = (val: number) => {
  suppliersInquire.value.pageSize = val
  suppliersList()
}
const handleCurrentChange = (val: number) => {
  suppliersInquire.value.currentPage = val
  suppliersList()
}
//查询供应商列表
const suppliersList = () => {
  suppliersSelectlist(suppliersInquire.value).then((data) => {
    tableData.value = data.data.records
    suppliersInquire.value.total = data.data.total
  })
}
//条件查询
const suppliersSelect = () => {
  suppliersSelectlist(suppliersInquire.value).then((data) => {
    tableData.value = data.data.records
  })
}
//重置
const suppliersReset = () => {
  suppliersInquire.value.erpCode = ''
  suppliersInquire.value.supplierName = ''
  suppliersList()
}

const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<User[]>([])
const iseditmultiple = ref(false)
const selectId = ref(0)

const materialone = (val: User[]) => {
  multipleSelection.value = val
  multipleSelection.value.forEach((element) => {
    selectId.value = element.id
  })
}
const materialall = (val: User[]) => {
  multipleSelection.value = val
}
// 删除供应商
const dialogFormVisible = ref(false)

const delform = () => {
  if (multipleSelection.value.length > 0) {
    ElMessageBox.confirm('你是否要删除掉这些数据?', '删除', {
      distinguishCancelAndClose: true,
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      confirmButtonClass: 'propfirmbtn'
    })

      .then(() => {
        suppliersdelete(selectId.value)
          .then((data) => {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            suppliersList()
          })
          .catch((err) => {
            ElMessage({
              type: 'error',
              message: err
            })
          })
      })
      .catch((action: Action) => {
        ElMessage({
          type: 'info',
          message: action === 'cancel' ? '取消删除' : ''
        })
      })
  }
}

interface RuleFormedit {
  id?: string
  createBy: string
  erpCode: string
  supplierName: string
  phone: string
  vatRegistrationNumber: string
  country: string
  province: string
  city: string
  streetSign: string
  language: string
  fax: string
  postcode: string
  website: string
  accountGroup: string
  headerDescription: string
}
const ruleFormedit = ref<RuleFormedit>({
  id: '',
  createBy: 'admin',
  erpCode: '',
  supplierName: '',
  phone: '',
  vatRegistrationNumber: '',
  country: '',
  province: '',
  city: '',
  streetSign: '',
  language: '',
  fax: '',
  postcode: '',
  website: '',
  accountGroup: '',
  headerDescription: ''
})
const editmultiple = () => {
  if (iseditmultiple.value) {
    suppliersedit(ruleFormedit.value)
      .then((data) => {
        ElMessage({
          type: 'success',
          message: '编辑成功'
        })
        dialogFormVisible.value = false
        suppliersList()
      })
      .catch((err) => {
        ElMessage({
          type: 'error',
          message: err
        })
      })
  } else {
    suppliersadd(ruleFormedit.value)
      .then((data) => {
        ElMessage({
          type: 'success',
          message: '新增成功'
        })
        dialogFormVisible.value = false
        suppliersList()
      })
      .catch((err) => {
        ElMessage({
          type: 'error',
          message: err
        })
      })
  }
}
// 修改供应商
const editform = () => {
  ruleFormedit.value.id = selectId.value.toString()
  iseditmultiple.value = true
  if (multipleSelection.value.length == 1) {
    dialogFormVisible.value = true
  }
}
// 增加供应商
const addform = () => {
  dialogFormVisible.value = true
}

// 查看供应商信息
const gomultipleinfo = (ids: string) => {
  router.push({
    name: 'longpress',
    query: { id: ids }
  })
}
const router = useRouter()
const route = useRoute()

interface RuleForm {
  materialName: string
  materialId: string
  materialType: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  materialName: '',
  materialId: '',
  materialType: ''
})

const formLabelWidth = '140px'

const formSizeedit = ref<ComponentSize>('default')
const ruleFormRefedit = ref<FormInstance>()

const rules = reactive<FormRules<RuleFormedit>>({
  // ERPid: [
  //   { required: true, message: '物料编号不能为空', trigger: 'blur' },
  //   { max: 64, message: '最多不能超过64个字符', trigger: 'blur' }
  // ],
  supplierName: [
    { required: true, message: '物料名称不能为空', trigger: 'blur' },
    { max: 64, message: '最多不能超过64个字符', trigger: 'blur' }
  ],
  phone: [{ max: 20, message: '最多不能超过20个字符', trigger: 'blur' }],
  vatRegistrationNumber: [
    { required: true, message: '规格不能为空', trigger: 'blur' },
    { max: 50, message: '最多不能超过64个字符', trigger: 'blur' }
  ],
  country: [
    {
      required: true,
      message: '请选择国家',
      trigger: 'change'
    }
  ]
})

const activeIndex = ref('1')
const handleSelect = (key: string) => {
  activeIndex.value = key
}

interface Productedit {
  id: string
  factory: string
  purchasgroup: string
  Deliverydays: string
  safestock: string
  profitcenter: string
}
const tableDataedit = ref<Productedit[]>([
  {
    id: '1',
    factory: '友达公司',
    purchasgroup: '第二组',
    Deliverydays: '15',
    safestock: '',
    profitcenter: ''
  }
])
const addmatereal = () => {
  const newmaterial = {
    id: (tableDataedit.value.length + 1).toString(),
    factory: '',
    purchasgroup: '',
    Deliverydays: '',
    safestock: '',
    profitcenter: ''
  }
  tableDataedit.value.push(newmaterial)
}
const delmatereal = (id: string) => {
  ElMessageBox.confirm('你是否要删除掉这条数据?', '删除', {
    distinguishCancelAndClose: true,
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonClass: 'propfirmbtn'
  })
    .then(() => {
      tableDataedit.value.forEach((item, index) => {
        if (item.id === id) {
          tableDataedit.value.splice(index, 1)
        }
      })
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch((action: Action) => {
      ElMessage({
        type: 'info',
        message: action === 'cancel' ? '取消删除' : 'Stay in the current route'
      })
    })
}

//导入
const importingOrder = ref(false)
const attachmentId = ref({ attachmentId: '666666' })
const loadfileheaders = {
  'Content-Type': 'multipart/form-data'
}
const uploading = (data) => {
  console.log(data, 23232)
  const formData = new FormData()
  formData.append('file', data.file)
  formData.append('attachmentId', data.data.attachmentId)
  suppliersimports(formData).then((data) => {
    console.log(data)
  })
}
//下载模板
const download = () => {
  const data = {}
  suppliersTemplate(null)
    .then((data) => {
      console.log(data)
    })
    .catch((err) => {})
}
</script>

<style lang="scss" scoped>
.box {
  background: #f8f8f8;
  width: 100%;
  // height: 89vh;
  box-sizing: border-box;
  padding: 15px 0;
}
.material-information {
  width: 98%;
  margin: 0px auto;
  background: #fff;
  border-radius: 10px;
  max-height: 350px;
  box-sizing: border-box;
  display: flex;
}

.materialinput {
  width: 30%;
}
.materialselect {
  width: 25%;
  margin-right: 5%;
}
.baseinfobtn {
  margin: auto;
  display: flex;
  flex-wrap: wrap;
}
.baseinfobtncenter {
  margin: auto;
  display: flex;
  flex-wrap: wrap;
}
.baseinfobtn-1 {
  background: #578c43;
  color: #fff;
  text-align: center;
  padding: 0 20px;
  height: 34px;
  line-height: 32px;
  border-radius: 10px;
  margin-right: 20px;
  cursor: pointer;
}
.baseinfobtn-2 {
  background: #fff;
  color: #333;
  text-align: center;
  padding: 0 20px;
  height: 34px;
  line-height: 32px;
  border-radius: 10px;
  border: 1px solid #eee;
  margin-right: 20px;
  cursor: pointer;
}

.baseinfobtn-2b {
  background: #fff;
  color: #a8abb2;
  text-align: center;
  padding: 0 20px;
  height: 34px;
  line-height: 32px;
  border-radius: 10px;
  border: 1px solid #eee;
  margin-right: 20px;
}

.material-addinformation {
  width: 98%;
  margin: 0px auto;
  background: #fff;
  border-radius: 10px;
  // max-height: 70vh;
  box-sizing: border-box;
  margin-top: 20px;
  padding: 3rem 0;
}
.el-form-item--default {
  margin-bottom: 0px !important;
}
::v-deep .el-pagination.is-background .el-pager li.is-active {
  background-color: #578c43;
}
.yuan {
  color: #578c43;
}
.yuanb {
  color: red;
}
.materialinputb {
  width: 48%;
  margin-bottom: 15px !important;
}
.materialselectb {
  width: 48%;
  margin-bottom: 15px !important;
}
.nemulist {
  --el-menu-bg-color: #fff !important;
  margin-top: 20px;
  border-bottom: 2px solid #e4e7ed;
}
.el-menu-item:hover {
  background-color: #fff !important;
  --el-menu-text-color: #333 !important;
  --el-menu-active-color: #578c43 !important;
  color: #578c43 !important;
}
.el-menu-item.is-active {
  background-color: #fff !important;
  color: #578c43 !important;
  border-bottom: 2px solid #578c43 !important;
}
.el-menu-item {
  color: #333 !important;
  position: relative;
  bottom: -2px;
}
.addmaterialbtn {
  background-color: #fff;
  color: #333;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  display: flex;
  font-size: 14px;
  box-sizing: border-box;
  padding: 12px 10px;
  width: 100px;
  margin-bottom: 15px;
}
.deltext {
  cursor: pointer;
  color: #578c43 !important;
  border: none;
}
.iconsy {
  position: relative;
  top: 3px;
  margin-right: 5px;
}
</style>
